import { find, concat, remove } from 'lodash'
import { getVideoInfo } from './video-details'
import { writeData } from './file-action'

// 默认规则
const constantRules = [
    {
        key: 0,
        title: '默认规则',
        description: '默认规则',
        rules: [
            // 来源
            '阳光电影',
            '电影天堂',
            // 语言
            '国语',
            '国粤',
            '中英',
            '日语',
            '双语',
            '双字',
            '双字幕',
            '中字',
            '原版',
            '字幕',
            // 清晰度
            '标清',
            '高清',
            '超清',
            'BD',
            'HD',
            'FHD',
            '360p',
            '480p',
            '720p',
            '720P',
            '1080p',
            '1080P',
        ],
    },
]
// 用户规则
var customRules = []

function setCustomRules(action, val) {
    const arr = Array.isArray(val) ? val : [val]
    if (action === 'remove') {
        for (const v of arr) {
            remove(customRules, (item) => item.key == v)
        }
    }
    if (action === 'add') {
        customRules = concat(customRules, arr)
    }
    console.log(customRules)
    writeData(customRules, 'customRules')
}

function initialFilter(str) {
    // 去掉url
    // eslint-disable-next-line
    let re = /[(https?|ftp|file):\/\/]?[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]/
    str = useRegular(str, re)
    // 去掉标点符号（除了·和-）
    re = /[^·(\u4e00-\u9fa5)(a-z)(A-Z)(0-9)-]/gm
    str = useRegular(str, re)
    return str
}

async function useRules(str, keys = [], useConstantRules = true) {
    if (useConstantRules) {
        str = initialFilter(str)
        for (const { rules } of constantRules) {
            str = replaceVal(rules, str)
        }
    }
    const _customRules = []
    // 确定已使用的自定义规则
    for (const key of keys) {
        const obj = find(customRules, { key })
        if (obj) {
            _customRules.push(obj)
        }
    }
    for (const { rules } of _customRules) {
        str = replaceVal(rules, str)
    }
    const info = await getVideoInfo(str)
    console.log(info)
    return { ...info }
}

/**
 * 使用正则表达式
 * @param {string} str 要处理的字符串
 * @param {string} re 正则表达式
 * @param {boolean} exclude
 */
function useRegular(str, re, exclude = true) {
    try {
        const arr = str.match(re)
        if (exclude) {
            return arr && arr.length > 0 ? replaceVal(arr, str) : str
        } else {
            return arr && arr.length > 0 ? arr : []
        }
    } catch (e) {
        console.log(str)
    }
}

function replaceVal(arr, str) {
    const _arr = arr.sort((a, b) => b.length - a.length)
    for (const val of _arr) {
        str = str.replace(val, '')
    }
    return str
}

function getRuleList() {
    const rules = []
    for (const val of concat(constantRules, customRules)) {
        rules.push(val)
    }
    return rules
}

export { setCustomRules, useRules, getRuleList, useRegular }
